<template>
  <div class="article-list" ref="article-list">
  <van-pull-refresh
  v-model="isRefreshLoading"
  :success-text="refreshSuccessText"
  :success-duration="1500"
  @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <article-item
      v-for="(article, index) in articles"
      :key="index"
      :article="article"
      ></article-item>
      <!-- <van-cell
      v-for="(article, index) in articles"
      :key="index"
      :title="article.title" /> -->
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
import { debounce } from 'lodash'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    return {
      articles: [],
      loading: false,
      finished: false,
      timestamp: null,
      isRefreshLoading: false,
      refreshSuccessText: '',
      scrollTop: 0
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  mounted () {
    const articleList = this.$refs['article-list']
    articleList.onscroll = debounce(() => {
      this.scrollTop = articleList.scrollTop
    }, 50)
  },
  activated () {
    this.$refs['article-list'].scrollTop = this.scrollTop
  },
  methods: {
    async onLoad () {
      // 1.请求获取数据
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      })
      // 2.把数据放到list数组中
      const { results } = data.data
      this.articles.push(...results)
      // 3.设置本次加载状态结束，它才可以判断是否需要加载下一次，否则就永远的停在这里
      this.loading = false
      // 4.数据全部加载完成
      if (results.length) {
        this.timestamp = data.data.pre_timestamp
      } else {
        this.finished = true
      }
    },
    async onRefresh () {
      // 下拉刷新 组件自己就会展示loading状态
      // 1. 请求获取数据
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1
      })
      // 2. 把数据放到数据列表中
      const { results } = data.data
      this.articles.unshift(...data.data.results)
      // 3. 关闭刷新状态
      this.isRefreshLoading = false
      this.refreshSuccessText = `更新了${results.length}条数据`
    }
  }
}
</script>

<style lang="less" scoped>
  .article-list {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 50px;
    top: 90px;
    overflow-y: auto;
  }
</style>
